package top.ywlog.permission.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.ywlog.permission.common.RequestHolder;
import top.ywlog.permission.common.request.RoleParam;
import top.ywlog.permission.dao.SysRoleMapper;
import top.ywlog.permission.exception.ParamException;
import top.ywlog.permission.model.SysRole;
import top.ywlog.permission.util.IpUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;

/**
 * @author: Durian
 * @date: 2020/10/24 20:47
 * @description:
 */
@Slf4j
@Service
public class SysRoleService
{
    @Resource
    private SysRoleMapper sysRoleMapper;

    @Transactional
    public void saveRole(RoleParam roleParam)
    {
        if (checkExist(roleParam.getName(), roleParam.getId()))
        {
            throw new ParamException("角色名已经存在");
        }
        SysRole role = SysRole.builder().name(roleParam.getName()).status(roleParam.getStatus()).type(roleParam.getType())
                .remark(roleParam.getRemark()).build();
        role.setOperator(RequestHolder.getCurrentUser().getUsername());
        role.setOperateIp(IpUtils.getRemoteIp(RequestHolder.getCurrentRequest()));
        role.setOperateTime(LocalDateTime.now());
        sysRoleMapper.insertSelective(role);
    }

    @Transactional
    public void updateRole(RoleParam roleParam)
    {
        if (checkExist(roleParam.getName(), roleParam.getId()))
        {
            throw new ParamException("角色名已经存在");
        }

        SysRole before = sysRoleMapper.selectByPrimaryKey(roleParam.getId());
        if (before == null)
        {
            throw new ParamException("待更新角色不存在");
        }
        SysRole after = SysRole.builder().id(roleParam.getId()).name(roleParam.getName()).status(roleParam.getStatus()).type(roleParam.getType())
                .remark(roleParam.getRemark()).build();
        after.setOperator(RequestHolder.getCurrentUser().getUsername());
        after.setOperateIp(IpUtils.getRemoteIp(RequestHolder.getCurrentRequest()));
        after.setOperateTime(LocalDateTime.now());
        sysRoleMapper.updateByPrimaryKeySelective(after);
    }

    private boolean checkExist(String name, Integer id)
    {
        return sysRoleMapper.countByName(name, id) > 0;
    }
}
